const express = require("express");
const app = express();
const session = require("express-session");
const cors = require("cors");
const path = require("path");
const xss = require("xss");

app.use(
  cors({
    origin: function (origin, callback) {
      console.log("cors", origin);
      // 允许所有请求origin
      callback(null, true);
    },
    credentials: true,
  })
);

const staticPath = path.join(__dirname, "../public");
app.use(express.static(staticPath));

app.use(express.json());

app.use(express.urlencoded({ extended: true }));

// xss 过滤
const myxss = new xss.FilterXSS({
  onTagAttr(tag, name, value, isWhiteAttr) {
    if (name === "style") {
      return `style="${value}"`;
    }
  },
});
app.use((req, res, next) => {
  for (const key in req.body) {
    const value = req.body[key];
    req.body[key] = myxss.process(value);
  }
  next();
});

const sessionMiddleware = session({
  secret: "test",
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }, // 如果使用 HTTPS，设置为 true
});

// console.log("sessionMiddleware init", sessionMiddleware);

app.use(sessionMiddleware);

app.use(require("./authorMiddware"));
app.use("/resources", require("./resourcesMiddware"));
app.use("/api/user", require("./userMiddware"));
app.use("/api/upload", require("./uploadMiddware"));

module.exports = {
  app,
  sessionMiddleware,
};
